# -*- codeing = utf-8 -*-
# @Time : 2021/5/1 15:36
# @Authon : Bin
# @Flie : dibin.py
# @Software : PyCharm


from selenium import webdriver
import time
import os
import webbrowser
from urllib.request import urlretrieve
import urllib.request
import json
import sys
import random
import getpass


def chromfile():
    chromfile = os.path.exists('chromedriver.exe')
    if (chromfile):
        pass
    else:
        print("浏览器驱动不存在，请先安装")
        time.sleep(5)
        sys.exit(0)


def Update():
    urlver = r"http://binfamily.gitee.io/yiban/shua.json"

    def downversion(urlver):
        head = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.146 Safari/537.36"
        }
        request = urllib.request.Request(urlver, headers=head)
        response = urllib.request.urlopen(request)
        html = response.read().decode("utf-8")
        return html

    html11 = downversion(urlver)
    versionpath = "version.json"

    try:
        def NewFile(pathv):
            newfile = open(pathv, "w+", encoding="utf-8")
            newfile.writelines(html11)
            newfile.close()
            # print("文件写入成功")

    except Exception as test:
        print(test)

    NewFile(versionpath)

    def loadversion():
        f = open("version.json", encoding='utf-8')  # 设置以utf-8解码模式读取文件，encoding参数必须设置，否则默认以gbk模式读取文件，当文件中包含中文时，会报错
        setting = json.load(f)
        family = setting['BaseSettings']['size']  # 注意多重结构的读取语法
        size = setting['fontSize']
        return family

    def fontgg():
        f = open("version.json", encoding='utf-8')  # 设置以utf-8解码模式读取文件，encoding参数必须设置，否则默认以gbk模式读取文件，当文件中包含中文时，会报错
        setting = json.load(f)
        size = setting['gg']
        return size

    def gg():
        f = open("version.json", encoding='utf-8')  # 设置以utf-8解码模式读取文件，encoding参数必须设置，否则默认以gbk模式读取文件，当文件中包含中文时，会报错
        setting = json.load(f)
        fa = setting['BaseSettings']['Notice']
        size = setting['fontSize']
        return fa

    print(gg())
    print(fontgg())
    print(" Copyright © 2021 xx职业技术学院易班发展中心 - 易班学生工作站. All Rights Reserved.")
    version = loadversion()
    if (version == 4.0502):
        # print("版本检验通过")
        os.remove(versionpath)
    else:
        print("版本不一致，请及时更新")
        os.remove(versionpath)
        webbrowser.open_new_tab('https://binfamily.gitee.io/#help')
        webbrowser.open_new_tab('http://binfamily.gitee.io/yiban/hzyauto.exe')
        sys.exit(0)


options = webdriver.ChromeOptions()


options.add_argument('disable-infobars')#隐藏"Chrome正在受到自动软件的控制"

# 更换头部

user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"

options.add_argument('user-agent=%s'%user_agent)
options.add_argument('lang=zh_CN.utf-8')
# webdriver.Chrome(options)

wb = webdriver.Chrome("chromedriver.exe")
wb.implicitly_wait(5)

pinglunlist = ["千锤万凿出深山，烈火焚烧若等闲——于谦《石灰吟》", "水色渌且明，令人思镜湖——李白《登单父陶少府半月台》", "月有盈亏花有开谢，想人生最苦离别——张鸣善《普天乐·咏世》",
               "遮莫圆明似前度，不知谁续广寒游——慧霖《闰中秋玩月》", "堂上谋臣尊俎，边头将士干戈——辛弃疾《西江月·堂上谋臣尊俎》"]
pllist = ["one", "two", "three", "four", "five"]


class caozuo:
    def qiandao(self):
        print("此功能暂未开放，请手动签到")
        core(mokuai())
        return False
        try:
            # 签到模块
            wb.find_element_by_css_selector('i[class="icon icon-sign guide2015_1-1"]').click()
            wb.find_element_by_xpath('//*[@id="sign-survey"]/dl/dd[1]').click()
            wb.find_element_by_css_selector('.dialog-btn a[class="dialog-confirm"]').click()
            wb.find_elements_by_css_selector('a[class="dialog-cancel"]').click()
            print('-------签到完成-------')
            core(mokuai())
        except Exception:
            print("-------你已经签到过-------")
            core(mokuai())

    def square(self):
        # 账号广场浏览公共群
        wb.get("https://www.yiban.cn/")
        wb.find_element_by_css_selector("a[class='guide-8']").click()
        wb.find_element_by_css_selector('ul[class ="pub-list clearfix"] a').click()
        time.sleep(2)
        for lis in range(1, 6):
            glq = wb.find_element_by_css_selector(
                'a[class="green"][id="view-groupinfo"][href="javascript:void(0);"]')
            glq.click()
            wb.find_element_by_xpath('//*[@id="group-list"]/ul/li[%d]/figure/figcaption/a' % lis).click()
            wb.back()
        print("-------账号广场执行成功-------")
        core(mokuai())

    def userinfo(self):  # 遍历访问个人主页
        for i in range(10, 60, 10):
            time.sleep(2)
            wb.get("http://www.yiban.cn/user/index/index/user_id/000000%s" % i)
        print("-------遍历个人主页成功-------")
        core(mokuai())

    def qun(self):
        # 公共群
        wb.get("http://www.yiban.cn/my/group/type/public")
        wb.find_element_by_css_selector(
            "body > div.group-guide > div.guide-step.guide-tag > a.guide-delete").click()
        ggq = wb.find_elements_by_css_selector('a[class="avatar avatar-m"]')
        m = int(input("请输入你需要执行操作的课群，下标从0开始表示第一个"))
        ggq[m].click()
        mainwindow = wb.current_window_handle
        for qunlist in range(1, 5):
            try:
                userlist = wb.find_element_by_xpath(
                    '/html/body/main/div/div/div/div[1]/section[3]/div[%d]/div/div[1]/a' % qunlist).click()
                # print(wb.title)
                for handle in wb.window_handles:
                    # 先切换到该窗口
                    wb.switch_to.window(handle)
                data_text = wb.find_element_by_css_selector('div[class="detail-forum-text"]')
                # print(data_text.text)
                context = random.choice(pinglunlist)
                wb.find_element_by_css_selector('textarea[class="box-area"]').send_keys(context)
                time.sleep(2)
                wb.find_element_by_css_selector('input[type="checkbox"][checked="true"]').click()
                time.sleep(2)
                wb.find_element_by_css_selector(
                    'a[class="comment-box-submit btn-blue y_box_submit"][data-type="comment"]').click()
                time.sleep(2)
                wb.switch_to.window(mainwindow)
            except Exception as e:
                print("公共群暂无可操作文章，程序即将返回")
                core(mokuai())
        print("-------公共群操作完成-------")
        core(mokuai())

    def toupiao(self):
        wb.get("http://www.yiban.cn/my/group/type/public")
        wb.find_element_by_css_selector(
            "body > div.group-guide > div.guide-step.guide-tag > a.guide-delete").click()
        ggq = wb.find_elements_by_css_selector('a[class="avatar avatar-m"]')
        m2 = int(input("请输入你需要执行操作的课群，下标从0开始表示第一个"))
        ggq[m2].click()
        mainwindow = wb.current_window_handle  # 当前窗口句柄
        for tlist in range(0, 4):
            try:
                toulist = wb.find_elements_by_css_selector('li div[class="box"]')
                toulist[tlist].click()
                # print(wb.title)

                for handle in wb.window_handles:
                    # 先切换到该窗口
                    wb.switch_to.window(handle)
                # 点赞
                wb.find_element_by_xpath('//*[@id="btn_like"]/div[1]').click()
                # 投票选择
                wb.find_element_by_xpath('//*[@id="vote_optionlist"]/div/table[1]').click()
                wb.find_element_by_xpath('//*[@id="vote_optionlist"]/div/table[2]').click()
                # 点击投票
                time.sleep(1)
                wb.find_element_by_css_selector('a[class="btn_vote"]').click()
                time.sleep(1)
                # 评论投票
                context2 = random.choice(pllist)
                wb.find_element_by_css_selector('.text_border input[type="text"]').send_keys(context2)
                time.sleep(1)
                # 点击评论
                wb.find_element_by_css_selector('div[class="aside-body content-body"] a[class="submit"]').click()
                time.sleep(1)
                wb.switch_to.window(mainwindow)
            except Exception as e:
                print("投票出现异常，即将返回窗口首句柄%s" % e)
                wb.switch_to.window(mainwindow)

        print('-------投票执行成功-------')
        core(mokuai())

    def addtoupiao(self):
        wb.get("http://www.yiban.cn/my/publishvote")
        try:
            title = random.choice(pllist)
            pr = random.choice(pinglunlist)
            wb.find_element_by_css_selector('div[class="container"] div[class="cf"] div input').send_keys(title)
            wb.find_element_by_xpath('/html/body/main/div/section/div[1]/div/ul[1]/li[1]/div[1]/input').send_keys(
                "选项1")
            wb.find_element_by_xpath('/html/body/main/div/section/div[1]/div/ul[1]/li[2]/div/input').send_keys(
                "选项2")
            wb.find_element_by_xpath('/html/body/main/div/section/div[1]/div/ul[1]/li[3]/div/input').send_keys(
                "选项3")
            wb.find_element_by_css_selector('textarea[class="textarea js-subjectTxt"]').send_keys(pr)
            wb.find_element_by_xpath('/html/body/main/div/section/div[1]/div/p[6]/label/div').click()
            sub = wb.find_elements_by_xpath('/html/body/main/div/section/div[1]/div/div[3]/ul[1]/li')
            print("请选择需要发布的群(推荐发布到网薪自动化)")
            value = 0
            for i in sub:
                value += 1
                print("群下标：%d   群昵称：%s" % (value, i.text))
            fanwei = int(input("请输入你要发布群的下标:"))
            wb.find_element_by_xpath(f'/html/body/main/div/section/div[1]/div/div[3]/ul[1]/li[{fanwei}]').click()

            wb.find_element_by_css_selector('a[class="btn btn-huge btn-blue btn-huge js-submit"]').click()
            print("发布成功，如需再次发送，请隔一分钟后在执行")
            core(mokuai())
        except Exception as e:
            print("发布投票出现异常，你还未加入自动化群，请先加入")
            print(e)
            core(mokuai())

    def addqun(self):
        try:
            wb.get('http://www.yiban.cn/newgroup/indexPub/group_id/1338291/puid/44712520')
            wb.find_element_by_css_selector('a[class="join-in btn btn-blue"][data-groupid="1338291"]').click()
            print("加群成功")
            core(mokuai())
        except Exception:
            print("你已经加过群，请勿重复使用此模块")
            core(mokuai())

    def help(self):
        webbrowser.open_new_tab('https://binfamily.gitee.io/#help')
        core(mokuai())


def login():
    wb.get("https://www.yiban.cn/login?go=http%3A%2F%2Fwww.yiban.cn%2F")

    userinfo = input("请输入账号")
    password = getpass.getpass(("请输入密码:"))  # getpass 在pycharm中无效

    wb.find_element_by_id("account-txt").send_keys(userinfo)
    wb.find_element_by_id("password-txt").send_keys(password)
    kw = wb.find_element_by_id("login-btn")
    kw.click()
    print("如果登录有验证码，请在易班页面输入验证码，并登录")


def mokuai():
    print("请选择需要执行的功能，输入数字即可--输入true访问帮助文档--输入false 退出程序")
    print("0.加入自动化网薪群(此功能每个用户只需执行一次) - 1.签到功能(不稳定) - 2.遍历学校账号广场 - 3.遍历个人主页 - 4.公共群微社区 - 5.公共群投票 - 6.发布投票")
    mokuaifunction = input("请输入序号：")
    return mokuaifunction


def core(id):
    if (id == "1"):
        caozuo.qiandao(1)
    elif (id == "2"):
        caozuo.square(1)
    elif (id == "3"):
        caozuo.userinfo(1)
    elif (id == "4"):
        caozuo.qun(1)
    elif (id == "5"):
        caozuo.toupiao(1)
    elif (id == "0"):
        caozuo.addqun(1)
    elif (id == "6"):
        caozuo.addtoupiao(1)
    elif (id == 'true'):
        caozuo.help(1)
    elif (id == "false"):
        print("------程序即将终止！------")
        wb.quit()
    else:
        print("你输入的序号有误，程序结束本次运行")


if __name__ == '__main__':
    chromfile()  # 驱动检测
    Update()  # 更新检测
    login()  # 登录主程序
    core(mokuai())  # 模块选择返回功能执行序号
